package controller

import (
	"crypto/md5"
	"fmt"
	"github.com/gin-gonic/gin"
	"jsjb/app/jsjb/model"
	"jsjb/setting"
	"jsjb/tools/jwt"
	"jsjb/tools/wx"
	"net/http"
	"strconv"
	"strings"
)

func Login(c *gin.Context) {
	//定义用户名和密码
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		fmt.Println("缺少用户名和密码")
		return
	}
	body, err := model.FindUser(username)
	if err != nil {
		fmt.Println(err)
		fmt.Println("该用户不存在")
		return
	}
	if body.Id == 0 {
		fmt.Println("该用户不存在")
		return
	}
	//执行两次md5,先password加密,然后加密的再连接salt加密一次
	mdPassword := fmt.Sprintf("%x", md5.Sum([]byte(fmt.Sprintf("%x%s", md5.Sum([]byte(password)), body.Salt))))
	if mdPassword != body.Password {
		fmt.Println("密码不正确")
		return
	}
	//拼接groupId
	b, _ := model.GetGroupIdByUid(body.Id)
	var gg []string
	for _, v := range b {
		gg = append(gg, v.GroupId)
	}
	body.Group = strings.Join(gg, ",")
	//获取其他字段信息
	orgSli := strings.Split(body.Orgid, ",")[0]
	orgId, _ := strconv.Atoi(orgSli)
	d, _ := model.RecallByOrgId(int32(orgId))
	body.OfficeId = d.OfficeId
	body.OfficeName = d.OfficeName
	body.OfficeType = d.OfficeType
	body.Townid = d.Townid

	//将用户信息进行jwt加密
	token, _ := jwt.GenToken(body)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登录成功",
		//"data": "{token:" + token + "}",
		"data": token,
	})

}
func GetUserPhoneNumber(c *gin.Context) {
	wechatConfig := setting.Conf.Wechat
	fmt.Println(wechatConfig)
	code := c.PostForm("code")
	if code == "" {
		fmt.Println("code不能为空")
	}

	appid := wechatConfig.Appid
	secret := wechatConfig.Secret
	fmt.Println(appid)
	fmt.Println(secret)
	wx.New(appid, secret).GetUserPhoneNumber()
}
